package com.polaris.live.ui.set.cover

import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R.color
import com.polaris.live.R.drawable
import com.polaris.live.adapter.party.PartyCoverRewardAdapter
import com.polaris.live.adapter.party.PartyCoverTypeAdapter
import com.polaris.live.adapter.party.PartyThemeTypeAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivitySetPartyCoverBinding
import com.polaris.live.dialog.common.ConfirmCanalDialog
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.resp.back_resp.PartyGameResp
import com.polaris.live.resp.back_resp.UserCoverResp
import com.polaris.live.resp.event.PartyExitEvent
import com.polaris.live.translation.R
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.UserUtils.isLevelZero
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.getLongOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.loadImage
import com.polaris.live.viewmodel.SetPartyImageViewModel
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * SetPartyCoverActivity
 *
 * @author Created by 半仙 on 2024/2/28/028 9:46
 */
class SetPartyCoverActivity :
    BaseVbActivity<SetPartyImageViewModel, ActivitySetPartyCoverBinding>() {

    //点击创建的时候是否需要先提交封面
    private var mIsNeedSubmit = false

    //是否提交封面后返回
    private var mIsNeedBack = false

    //是否有上传的封面照但是没有提交
    private var mIsHavaUpload = false

    private var mUserCoverResp: UserCoverResp? = null

    private val mPartyType = CommonConst.PartyType.PARTY

    private val mPartyTypeAdapter by lazy { PartyCoverTypeAdapter() }

    private val mPartyRewardAdapter by lazy { PartyCoverRewardAdapter() }

    private val mPartyThemeTypeAdapter by lazy { PartyThemeTypeAdapter() }

    //以下的参数是默认选中的参数    如果不需要可不传
    //游戏id
    private val mGameId by lazy { intent.getIntOrString("gameId", 0) }

    private var mVoiceAndVideoType = VOICETYPE

    //下面两个  要么都传   要么都不传    不要单独传一个
    //游戏奖励类型
    private val mRewardType by lazy {
        intent.getIntOrString(
            "rewardType",
            CommonConst.PartyAssetType.COIN
        )
    }

    private var mRoomName: String? = null

    private var mLastRoomName: String? = null

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBar(mBinding.llTitle)
            .navigationBarDarkIcon(true)
            .statusBarDarkFont(true)
            .init()
    }

    //游戏奖励数量   免费的话这个传0就行
    private val mRewardNum by lazy { intent.getLongOrString("rewardNum", 0) }

    override fun initView(savedInstanceState: Bundle?) {
        ViewUtils.setMargin(mBinding.privilegePromptTv, bottomMargin = NavigationBarUtils.getNavigationBarHeight(this))
        mBinding.selectPartyRecycler.apply {
            adapter = mPartyTypeAdapter
            var flexboxLayoutManager = FlexboxLayoutManager(this@SetPartyCoverActivity)
            flexboxLayoutManager.flexDirection = FlexDirection.ROW
            flexboxLayoutManager.flexWrap = FlexWrap.WRAP
            flexboxLayoutManager.justifyContent = JustifyContent.FLEX_START
            layoutManager = flexboxLayoutManager
            itemAnimator = null
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State,
                ) {
                    outRect.top = 6.autoDp
                }
            })
        }
        mBinding.themeRecycler.apply {
            adapter = mPartyThemeTypeAdapter
            var flexboxLayoutManager = FlexboxLayoutManager(this@SetPartyCoverActivity)
            flexboxLayoutManager.flexDirection = FlexDirection.ROW
            flexboxLayoutManager.flexWrap = FlexWrap.WRAP
            flexboxLayoutManager.justifyContent = JustifyContent.FLEX_START
            layoutManager = flexboxLayoutManager
            itemAnimator = null
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State,
                ) {
                    outRect.top = 6.autoDp
                }
            })
        }

        mBinding.rewardRecycler.apply {
            adapter = mPartyRewardAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            itemAnimator = null
        }
        initListener()
        initObserver()
        mBinding.done.alpha = AppConst.NOTCLICK
        mBinding.done.isEnabled = false
        mBinding.selectPartyRecycler.visibility = View.GONE

        mViewModel.getPartyRoom()
        mViewModel.getUserCover(mPartyType)
        mViewModel.getPartyGame()
        mViewModel.requestPartyTheme()
        mBinding.privilegePromptTv.getPartyCoverScroll(mViewModel)
    }

    private fun selectUi() {
        if (mVoiceAndVideoType == VOICETYPE) {
            val item = mPartyTypeAdapter.getSelectItem()
            if (item is PartyGameResp) {
                mBinding.llSelectReward.visibility = View.VISIBLE
                mBinding.llRewardNum.visibility = View.VISIBLE
            } else {
                mBinding.llSelectReward.visibility = View.GONE
                mBinding.llRewardNum.visibility = View.INVISIBLE
            }

            mBinding.selectPartyRecycler.visibility = View.VISIBLE
            mBinding.selectTypeTitle.visibility = View.VISIBLE
            mBinding.selectTypeTitle.setTextColor(ColorUtils.getColor(color.black))
            mBinding.voiceLl.setBackgroundResource(drawable.r4_gradient_fa3a9e_fe1849_fc772a)

            mBinding.videoLl.setBackgroundResource(drawable.r4_back_000000_5)
        } else {
            mBinding.selectPartyRecycler.visibility = View.GONE
            mBinding.selectTypeTitle.visibility = View.GONE
            mBinding.selectTypeTitle.setTextColor(ColorUtils.getColor(color.black))

            mBinding.voiceLl.setBackgroundResource(drawable.r4_back_000000_5)
            mBinding.videoLl.setBackgroundResource(drawable.r4_gradient_fa3a9e_fe1849_fc772a)

            mBinding.llSelectReward.visibility = View.GONE
            mBinding.llRewardNum.visibility = View.INVISIBLE
        }

    }

    private fun initObserver() {
        mViewModel.mUserCoverLiveData.observe(this) { resultState ->
            mBinding.done.visibility = View.VISIBLE
            parseState(resultState, {
                mUserCoverResp = it
                selectUi()
                if (it.url != null) {
                    Glide.with(this).loadImage(it.url).into(mBinding.selectImage)
                    mBinding.selectImage.visibility = View.VISIBLE
                    mBinding.describeTv.text = StringUtils.getString(R.string.replace_photos)
                }
                //机审拒绝都不可以点击
                canClickBottom()
                //审核中
                if (it.status != null && it.status == AppConst.CoverPhoto.REVIEWING || it.status == AppConst.CoverPhoto.UNDER_REVIEW) {
                    mBinding.describeTv.text = StringUtils.getString(R.string.under_review_cover)
                }
                //如果图片还没有提交
                if (it.status != null && it.status == AppConst.CoverPhoto.ISREADYUP) {
                    mIsNeedSubmit = true
                }
            })
        }
        mViewModel.mUploadCoverLiveData.observe(this) { resultState ->
            dismissLoading(waitTime = 0)
            mBinding.describeTv.text = StringUtils.getString(R.string.replace_photos)
            parseState(resultState, {
                mUserCoverResp = it
                mIsHavaUpload = true
                if (it.status == AppConst.CoverPhoto.ISREADYUP) {
                    photoIsGood()
                    canClickBottom()
                    mIsNeedSubmit = true
                    selectUi()
                }
            }, {
                mBinding.done.alpha = AppConst.NOTCLICK
                mBinding.done.isEnabled = false
                mIsNeedSubmit = false
                photoNotGood(it.errorMsg)
            })
        }
        mViewModel.mSubmitCoverLiveData.observe(this) { resultState ->
            mIsNeedSubmit = false
            mIsHavaUpload = false
            parseState(resultState, {
                mUserCoverResp = it
                if (mIsNeedBack) {
                    finish()
                } else {
                    //开启派对
                    letGoParty()
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.mPartyGameLiveData.observe(this) { resultState ->
            mBinding.llBottomTypeSelect.visibility = View.VISIBLE
            mBinding.scrollView.post {
                mBinding.scrollView.scrollTo(0, mBinding.scrollView.getChildAt(0).height)
            }
            parseState(resultState, { list ->
                mPartyTypeAdapter.setList(list)
                mPartyTypeAdapter.addData(0, PartyCoverTypeAdapter.PARTY)
                //初始化默认选中
                val index = list.indexOfFirst { it.id == mGameId }
                val item = list.getOrNull(index)
                //根据类型找对应的下标
                val rewardIndex =
                    item?.prices?.indexOfFirst { it.assetType == mRewardType }
                        .takeIf { it != -1 } ?: 0

                //如果没有传奖励金额，则默认取对应游戏的对应类型的对应第一位价格
                val firstPrices = item?.prices?.getOrNull(rewardIndex)
                val showRewardNum =
                    if (mRewardNum == 0L && firstPrices?.assetType != CommonConst.PartyAssetType.FREE) {
                        firstPrices?.prices?.getOrNull(0) ?: 0L
                    } else {
                        mRewardNum
                    }

                onRoomTypeSelect(
                    if (index == -1) 0 else index + 1,
                    rewardIndex,
                    showRewardNum
                )
                val rewardType = item?.prices?.get(rewardIndex)?.assetType
                mBinding.ivRewardsIcon.setImageResource(
                    CommonUtils.invokeGameRewardRoundIcon(rewardType ?: 0)
                )
                changeBack()
            })
        }
        /**
         * 获取派对主题
         */
        mViewModel.mPartyThemeLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mPartyThemeTypeAdapter.setList(it)
                it.getOrNull(0)?.let { bean ->
                    setThemeTemplate(bean.template)
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomName?.isNotEmpty() == true) {
                    mBinding.etName.setText(it.roomName)
                    mBinding.tvTextLength.text = "${it.roomName.length}/20"
                } else {
                    canClickBottom()
                }
                mLastRoomName = it.roomName
                mRoomName = it.roomName
            })
        }
        mViewModel.mChangeNameLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mLastRoomName = mRoomName
                letGoParty()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun initListener() {

        mBinding.voiceLl.setOnSingleClickListener {
            mVoiceAndVideoType = VOICETYPE
            selectUi()
            val data = mPartyTypeAdapter.getSelectItem() ?: return@setOnSingleClickListener
            if (data !is PartyGameResp) {
                mBinding.themeLl.visibility = View.VISIBLE
            }
        }
        mBinding.videoLl.setOnSingleClickListener {
            mVoiceAndVideoType = VIDEOTYPE
            mBinding.themeLl.visibility = View.GONE
            selectUi()
        }
        mBinding.setLiveSelect.setOnSingleClickListener {
            val isAuditing =
                mUserCoverResp?.status == AppConst.CoverPhoto.UNDER_REVIEW || mUserCoverResp?.status == AppConst.CoverPhoto.REVIEWING
            if (isAuditing) {
                ToastGravity.showGravity(StringUtils.getString(R.string.cover_auditing))
                return@setOnSingleClickListener
            }
            if (mUserCoverResp?.allowedUpload == true) {
                XPopup.Builder(this)
                    .moveUpToKeyboard(false)
                    .isDestroyOnDismiss(true)
                    .asCustom(SelectImagePopup(this, onSelectIt = { type ->
                        when (type) {
                            SelectImagePopup.CAMERA -> {
                                CropUtils.startCamera(this, { result ->

                                    CropUtils.startCrop(this, result, 5f, 5f)
                                }, {})
                            }

                            else -> {
                                CropUtils.startAlbum(this, { uploadPhoto(it) }, {}, 5f, 5f)
                            }
                        }
                    }))
                    .show()
            } else {
                ToastGravity.showGravity(R.string.more_than_twice)
            }
        }
        mBinding.done.setOnSingleClickListener {
            if (!mBinding.llBottomTypeSelect.isVisible) return@setOnSingleClickListener
            mIsNeedBack = false
            if (mIsNeedSubmit) {
                onSubmitCover()
            } else {
                EventBus.getDefault().post(PartyExitEvent(true))
                //开启派对
                letGoParty()
            }
        }
        mBinding.bvTitle.setOnLeftClientListener {
            mIsNeedBack = true
            showConfirm()
        }

        mPartyTypeAdapter.setOnItemClickListener { _, _, position ->
            onRoomTypeSelect(position)
        }

        mPartyThemeTypeAdapter.setOnItemClickListener { _, _, position ->
            mPartyThemeTypeAdapter.data.getOrNull(position)?.let {
                setThemeTemplate(it.template)
            }

            mPartyThemeTypeAdapter.setSelect(position)
        }
        mPartyRewardAdapter.setOnItemClickListener { _, _, position ->
            val item = mPartyRewardAdapter.getItem(position)
            if (UserManager.getUser().isLevelZero()) {
                PublicTipsPopup.show(
                    this, this,
                    StringUtils.getString(R.string.prompt),
                    StringUtils.getString(R.string.open_game_level_low_tips),
                    StringUtils.getString(R.string.sure),
                    StringUtils.getString(R.string.recharge),
                ) {
                    GlobalPopupManager.showRechargePopup(
                        this,
                        mViewModel,
                        isNeedBottom = false
                    )
                }
                return@setOnItemClickListener
            }
            mPartyRewardAdapter.setSelect(position)
            mBinding.tvMultipleNum.text = item.prices?.getOrNull(0)?.toString()
            mBinding.ivRewardsIcon.setImageResource(CommonUtils.invokeGameRewardRoundIcon(item.assetType))
            changeBack()
            if (item.assetType == CommonConst.PartyAssetType.FREE) {
                mBinding.llRewardNum.visibility = View.INVISIBLE
            } else {
                mBinding.llRewardNum.visibility = View.VISIBLE
            }
        }
        //减少按钮
        mBinding.ivReduceNum.setOnClickListener {
            changeBack(false)
        }
        //增加按钮
        mBinding.ivAddNum.setOnClickListener {
            changeBack(true)
        }
        //房间名字输入框
        mBinding.etName.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                val name = mBinding.etName.text.toString()
                mBinding.tvTextLength.text = "${name.length}/20"
                mRoomName = name
                if (name.isNotEmpty()) {
                    canClickBottom()
                } else {
                    mBinding.done.alpha = AppConst.NOTCLICK
                    mBinding.done.isEnabled = false
                }
            }
        })
    }

    //添加或减少奖励数量时修改按钮颜色
    private fun changeBack(isAdd: Boolean? = null) {
        val prices = mPartyRewardAdapter.getSelectItem()?.prices
        val numPrice = mBinding.tvMultipleNum.text?.toString()?.toLongOrNull() ?: return
        val indexOf = prices?.indexOf(numPrice) ?: return
        var changeIndex = indexOf

        if (isAdd == false) {
            if (indexOf != 0) {
                changeIndex = indexOf - 1
                mBinding.tvMultipleNum.text = prices[indexOf - 1].toString()
            }
        } else if (isAdd == true) {
            if (indexOf != prices.size - 1) {
                changeIndex = indexOf + 1
                mBinding.tvMultipleNum.text = prices[indexOf + 1].toString()
            }
        }

        if (changeIndex > 0) {
            mBinding.ivReduceNum.setBackgroundResource(drawable.r4_gradient_fa3a9e_fe1849_fc772a)
        } else {
            mBinding.ivReduceNum.setBackgroundResource(drawable.r4_back_f1f1f1)
        }

        if (changeIndex < prices.size - 1) {
            mBinding.ivAddNum.setBackgroundResource(drawable.r4_gradient_fa3a9e_fe1849_fc772a)
        } else {
            mBinding.ivAddNum.setBackgroundResource(drawable.r4_back_f1f1f1)
        }
    }

    /**
     * 设置主题模版
     */
    private fun setThemeTemplate(path: String) {
        Glide.with(this)
            .load(ImageUtils.imgPath(path))
            .placeholder(drawable.back_e8e8e8)
            .into(mBinding.templateImg)
    }

    //房间选择     首次进进入页面才会有后面的参数  如果主动切换的话是不用传后面的参数的
    private fun onRoomTypeSelect(position: Int, rewardType: Int? = null, price: Long? = null) {
        val item = mPartyTypeAdapter.getItemOrNull(position) ?: return
        mPartyTypeAdapter.setSelect(position)
        //每次切换房间类型就把所有值恢复默认一次
        if (item is PartyGameResp) {
            mBinding.llSelectReward.visibility = View.VISIBLE
            mBinding.themeLl.visibility = View.GONE
            val itemPrices = (mPartyTypeAdapter.getSelectItem() as PartyGameResp).prices
            mPartyRewardAdapter.setList(itemPrices)
            if (price != null && price != 0L) {
                mBinding.tvMultipleNum.text = price.toString()
            } else {
                val pricesItem = itemPrices[0]
                mBinding.ivRewardsIcon.setImageResource(
                    CommonUtils.invokeGameRewardRoundIcon(pricesItem.assetType)
                )
                mBinding.tvMultipleNum.text = pricesItem.prices?.getOrNull(0)?.toString()
            }
            if (rewardType != null) {
                mPartyRewardAdapter.setSelect(rewardType)
                val assetType =
                    item.prices.getOrNull(rewardType)?.assetType ?: CommonConst.PartyAssetType.COIN
                mBinding.ivRewardsIcon.setImageResource(CommonUtils.invokeGameRewardRoundIcon(assetType))
            } else {
                mPartyRewardAdapter.setSelect(0)
            }
        } else {
            mBinding.llSelectReward.visibility = View.GONE
            mBinding.themeLl.visibility = View.VISIBLE
        }

        mBinding.llRewardNum.visibility = View.VISIBLE

        //没有等级的用户，默认选中免费
        val finalPrice = if (UserManager.getUser().isLevelZero()) {
            0L
        } else {
            price
        }
        //如果prices为null就可以理解选择免费了
        if (finalPrice != null && finalPrice == 0L) {
            val index =
                mPartyRewardAdapter.data.indexOfFirst { it.assetType == CommonConst.PartyAssetType.FREE }
            mPartyRewardAdapter.setSelect(index)
            mBinding.llRewardNum.visibility = View.INVISIBLE
        }
        changeBack()
    }

    private fun letGoParty() {
        val name = mRoomName
        if (mLastRoomName != name && name?.isNotEmpty() == true) {
            mViewModel.changeRoomName(name)
            return
        } else if (name.isNullOrBlank()) {
            ToastGravity.showGravity(StringUtils.getString(R.string.name_spaces_empty))
            return
        }


        if (mVoiceAndVideoType == VOICETYPE) {
            val item = mPartyTypeAdapter.getSelectItem()
            if (item is PartyGameResp) {
                val rewardItem = mPartyRewardAdapter.getSelectItem()
                val (rewardCoin, rewardType) = if (rewardItem?.prices?.isEmpty() == true) {
                    0L to (rewardItem.assetType)
                } else {
                    (mBinding.tvMultipleNum.text.toString().toLongOrNull()
                        ?: 0) to (rewardItem?.assetType ?: 0)
                }
                //开启游戏房
                StartLiveProxy.builder(this)
                    .startGamePartyLive(
                        mViewModel, LiveConst.Type.PARTY_GAME_LIVE, item.id,
                        rewardType,
                        rewardCoin,
                        name
                    ) { finish() }
            } else {//如果不是PartyGameResp  就开启仅派对
                when (item) {
                    PartyCoverTypeAdapter.PARTY -> {
                        StartLiveProxy.builder(this)
                            .startPartyLive(
                                mViewModel,
                                LiveConst.Type.PARTY_LIVE,
                                mPartyThemeTypeAdapter.getSelectItem()?.theme,
                                name
                            ) {
                                finish()
                            }
                    }

                    PartyCoverTypeAdapter.VIDEOPARTY -> {
                        StartLiveProxy.builder(this)
                            .startPartyLive(mViewModel, LiveConst.Type.VIDEO_PARTY, null, name) {
                                finish()
                            }
                    }
                }

            }
        } else {
            StartLiveProxy.builder(this)
                .startPartyLive(mViewModel, LiveConst.Type.VIDEO_PARTY, null) {
                    finish()
                }
        }

    }

    override fun onBackPressed() {
        mIsNeedBack = true
        showConfirm()
    }

    private fun showConfirm() {
        if (mIsHavaUpload) {
            XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .asCustom(
                    ConfirmCanalDialog(this,
                        StringUtils.getString(R.string.is_save_cover),
                        StringUtils.getString(R.string.submit_and_back),
                        onConfirmCallback = {
                            onSubmitCover()
                        },
                        onCanalCallback = {
                            finish()
                        }
                    )
                ).show()
        } else {
            finish()
        }
    }

    private fun onSubmitCover() {
        //提交封面照
        mViewModel.submitCover(mPartyType)
    }

    //图片上传
    private fun uploadPhoto(photoUrl: String) {
        mBinding.passwordDangerous.visibility = View.INVISIBLE
        mBinding.done.alpha = AppConst.NOTCLICK
        mBinding.done.isEnabled = false

        showLoading(waitTime = 0)
        val coverType = if (mPartyType == CommonConst.PartyType.PARTY) {
            AppConst.UpLoad.PARTY_COVER_PHOTO
        } else {
            AppConst.UpLoad.GAME_COVER_PHOTO
        }

        ImageUtils.s3Upload(photoUrl, coverType, 1024, callback =
        object : S3UploadCallback {
            override fun onSuccess(
                url: String,
                size: Pair<Int, Int>?,
            ) {
                lifecycleScope.launch {

                    Glide.with(this@SetPartyCoverActivity).load(photoUrl)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(mBinding.selectImage)
                    mBinding.selectImage.visibility = View.VISIBLE

                    mBinding.passwordDangerous.visibility = View.VISIBLE
                    mBinding.setLiveImageIv.visibility = View.GONE
                    mBinding.setLiveImageDetail.text =
                        StringUtils.getString(R.string.upload_succee)
                }

                //上传封面
                mViewModel.uploadCover(mPartyType, url)
            }

            override fun onFailure(t: Throwable) {
                LogExt.logE("--net", t)

                ToastGravity.showGravity(t.message)

                dismissLoading()
            }
        })
    }

    //图片可以 ，准备提交
    private fun photoIsGood() {
        mBinding.passwordDangerous.visibility = View.VISIBLE
        mBinding.setLiveImageIv.visibility = View.VISIBLE

        mBinding.setLiveImageDetail.text = StringUtils.getString(R.string.ai_is_ok)
        mBinding.setLiveImageDetail.setTextColor(Color.parseColor("#29D000"))
        mBinding.setLiveImageIv.setImageResource(com.polaris.live.common.R.drawable.ic_correct)
    }

    //图片不合格
    private fun photoNotGood(errorMessage: String) {
        mBinding.passwordDangerous.visibility = View.VISIBLE
        mBinding.setLiveImageIv.visibility = View.VISIBLE
        mBinding.setLiveImageDetail.setTextColor(Color.parseColor("#FE4F3C"))
        mBinding.setLiveImageIv.setImageResource(drawable.ic_delete_account_warn_red)
        mBinding.setLiveImageDetail.text = errorMessage
        mIsHavaUpload = false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            data?.let { result ->
                val file = UriUtils.uri2File(UCrop.getOutput(result))
                file?.let { uploadFile ->
                    uploadPhoto(uploadFile.absolutePath)
                }
            }
        } else if (resultCode == RESULT_CANCELED && requestCode == UCrop.REQUEST_CROP) {
            CropUtils.startCamera(this, { result ->
                CropUtils.startCrop(this, result, 5f, 5f)
            }, {})
        }
    }

    private fun canClickBottom() {
        if (mUserCoverResp?.status == AppConst.CoverPhoto.ISREADYUP) {
            if (mRoomName?.isNotEmpty() == true) {
                mBinding.done.alpha = 1.0F
                mBinding.done.isEnabled = true
            }
        } else {
            if (mUserCoverResp?.status != null && mUserCoverResp?.status != AppConst.CoverPhoto.REVIEW_NOT && mUserCoverResp?.status != AppConst.CoverPhoto.REVIEWING) {
                if (mRoomName?.isNotEmpty() == true) {
                    mBinding.done.alpha = 1.0F
                    mBinding.done.isEnabled = true
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.privilegePromptTv.reset()
    }

    companion object {

        const val VOICETYPE = 1
        const val VIDEOTYPE = 2
    }
}